<template>
  <div>
    <section class="container" id="lists" name="lists">
      <header class="breadcrumb-wrap">
        <el-breadcrumb class="breadcrumb pull-left" separator=">">
          <span class="pull-left">当前位置：</span>
          <el-breadcrumb-item>
            <nuxt-link class="text-primay-hover" :to="{ path: '/' }">首页</nuxt-link>
          </el-breadcrumb-item>
          <el-breadcrumb-item>商城</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="pull-right search-total">
          共找到{{ totalResult }}条 <span v-if="keyword">“<span class="text-primay keyword text-overflow"
                                                            :title="keyword">{{ keyword }}</span>”的</span>商品
        </div>
      </header>


      <!-- 搜索条件 -->
      <SearchProduct class="search-product " :lists="lists" @change="change" @clear="clear"></SearchProduct>

      <!--你是不是在找-->
      <Recommend v-if="recomdWords.length > 0" url="/mall" :data="recomdWords"></Recommend>

      <!--排序-->
      <SortProduct :show-type="showType"
                   @changePage="changePage"
                   @changeShowType="changeShowType"
                   @sortChange="sortChange"
                   :current-page="currentPage"
                   :total-page="totalPage"
                   class="sort-product"
                   :o-sort="oSort"></SortProduct>

      <!--横排商品-->
      <div class="single-product" v-show="showType === 2">
        <Product v-for="product in goods" :product="product" :key="product.goodsId" class="product"></Product>
      </div>

      <!--栅格商品-->
      <div class="grid-product " v-show="showType === 1">
        <ProductCard v-for="product in goods" :product="product" :key="product.goodsId" class="product"></ProductCard>
      </div>

      <!--没有数据-->
      <div class="no-result" v-if="goods.length === 0">
        <p>没有找到<span v-if="keyword"> 与“ <strong class="keyword text-overflow" :title="keyword">{{ keyword
          }}</strong>”</span>相关的商品，请重新筛选条件。</p>
      </div>

      <!-- 分页 -->
      <el-pagination
        v-if="totalPage > 1"
        class="pagination"
        @current-change="changePage"
        :current-page.sync="currentPage"
        :page-count="totalPage"
        layout="prev, pager, next, jumper">
      </el-pagination>

    </section>
  </div>
</template>

<script>
  import axios from '~/plugins/axios'
  import {ObjectMap} from '~/plugins/utils'

  // 搜索
  import SearchProduct from '~/components/SearchProduct'

  // 你是不是在找
  import Recommend from '~/components/Recommend'

  // 排序分页条
  import SortProduct from '~/components/SearchProduct/SortBar.vue'
  import ProductCard from '~/components/ProductCard.vue'
  import Product from '~/components/Product.vue'

  export default {
    data () {
      return {
        recomdWords: [],
        oSort: {
          filed: '',
          sortStyle: 'Desc'
        }
      }
    },

    mounted () {
      let keyword
      if (typeof this.keyword === 'string') {
        keyword = this.keyword.trim()
      }
      if (keyword) {
        // 获取你是不是在找
        axios.get('/search/recommend_word', {
          params: {
            keywordType: 0,
            keyword: keyword
          }
        }).then(data => {
          this.recomdWords = data.data.data
          return this.recomdWords
        })

        // 保存搜索关键字
        axios.post('/search/saveKeyword', {
          keywordType: 0,
          keyword: keyword
        })
      }
    },

    head () {
      let seo = {
        title: `${this.keyword}_${this.keyword}价格_${this.keyword}供应 - 聚贸矿产`,
        desc: `聚贸矿产在线交易平台，提供海量${this.keyword}供求信息、众多${this.keyword}供应商，汇集众多供应商的${this.keyword}价格，提供金融、仓储、物流、第三方支付等增值服务`
      }

      return {
        title: seo.title,
        meta: [{
          hid: 'description',
          name: 'description',
          content: seo.desc
        }]
      }
    },

    async asyncData ({store, query, route}) {

      // 矿产分类
      const cates = store.state.cates.cates || []

      // 品类列表
      let categorys = []

      // 港口
      let ports = []

      // 存放地
      let trades = store.state.area.trade || []

      // 交货地ID
      const trade = query.trade

      // 港口ID
      const port = query.p

      // 品种
      let variety = query.variety

      // 品类
      let category = query.category

      // 港口map
      const storePorts = store.state.area.ports

      // 如果有选中品种
      // 就去获取该品种下的品类列表
      if (variety) {
        let v = cates.find((item) => item.id === parseInt(variety, 10)) || {}
        categorys = v.categoryList || []
      }

      // 获取交货地
      if (!Array.isArray(trades) || trades.length < 1) {
        const {data: {data}} = await axios.get(`/search/findTradeAreaList`)
        data.forEach(item => {
          item.name = item.placeName
          item.id = item.placeCode
        })
        trades = data || []
        store.commit('SET_TRADEAREA', trades)
      }
      // 如果有选中交货地
      // 就需要获取该交货地下的港口
      if (trade) {
        ports = storePorts[trade]
        console.log(ports)
        // 在store中不存在
        // 从服务端请求数据
        if (!Array.isArray(ports) || ports.length < 1) {
          const {data: data = []} = await axios.get(`/search/findTradePortList/${trade}`).then((data) => data.data)
          data.forEach(item => {
            item.name = item.placeName
            item.id = item.placeCode
          })

          ports = data
          store.commit('SET_PORT', {data: data, tradeId: trade})
        }
      }

      let filed = query.filed
      let sortStyle = query.sortStyle
      let showType = parseInt(query.showType, 10) || 2

      let sort
      if (filed && sortStyle) {
        sort = filed + ' ' + sortStyle
      }

      let point = ''
      if (trade) {
        point += trade
      }

      if (port) {
        point += '>>' + port
      }

      // 查询条件
      const qu = {
        // 品类
        goodsCategoryGrade1Id: variety || undefined,

        // 品名
        goodsCategoryGrade2Id: category || undefined,

        // 存放地
        goodsAttr__deliveryPoint: point || undefined,

        // 页码
        currentPage: query.page || 1,

        // 每页条数
        pageSize: 15,

        // 关键字
        keyword: query.q,

        sort: sort
      }

      // 获取数据
      const [{
        result: goods = [],
        totalPage = 0,
        totalResult = 0
      }] = await Promise.all([
        axios.get('/search/goods', {params: qu}).then(data => data.data.data)
      ])

      return {
        query: query,
        keyword: query.q || '',
        currentPage: parseInt(query.page, 10) || 1,
        goods,
        // 来源判断是 search 还是 商城  商城1 搜索不传
        totalPage,
        totalResult,
        variety,
        category,
        trade,
        showType,
        port,
        oSort: {filed, sortStyle},
        lists: [
          {
            type: 'variety',
            label: '品类',
            isMultiple: false,
            isShowMore: false,
            data: cates,
            model: variety,
            checks: []
          },

          {
            type: 'category',
            label: '品种',
            isMultiple: false,
            isShowMore: false,
            data: categorys,
            model: category,
            checks: []
          },

          {
            type: 'trade',
            label: '交货地',
            isMultiple: false,
            isShowMore: false,
            data: trades,
            model: trade,
            checks: []
          },

          {
            type: 'port',
            label: '港口',
            isMultiple: false,
            isShowMore: false,
            data: ports,
            model: port,
            checks: []
          }
        ]
      }
    },

    methods: {
      /**
       *  改变显示方式
       */
      changeShowType (type) {
        this.showType = type
        this.setRouter()
      },

      /**
       * 获取商品
       *
       */
      async getGoods () {
        let sort
        if (this.oSort.filed && this.oSort.sortStyle) {
          sort = this.oSort.filed + ' ' + this.oSort.sortStyle
        }

        let point = ''
        if (this.trade) {
          point += this.trade
        }

        if (this.port) {
          point += '>>' + this.port
        }

        const qu = {
          // 品类
          goodsCategoryGrade1Id: this.variety,

          // 品名
          goodsCategoryGrade2Id: this.category || undefined,

          // 存放地
          goodsAttr__deliveryPoint: point || undefined,

          // 页码
          currentPage: this.currentPage || 1,

          // 每页条数
          pageSize: 15,

          // 关键字
          keyword: this.keyword,

          sort: sort
        }

        // 获取数据 {goods: result = [], totalPage = 0, totalResult = 0}
        const {result: goods = [], totalPage = 0, totalResult = 0} = await axios.get('/search/goods', {params: qu}).then(data => data.data.data)
        
        this.goods = goods
        this.totalPage = totalPage
        this.totalResult = totalResult
      },

      /**
       *  排序改变
       */
      sortChange (oSort) {
        this.oSort.filed = oSort.filed
        this.oSort.sortStyle = oSort.sortStyle

        this.setRouter()
      },

      /**
       *  搜索组件内部清除所有
       */
      clear () {
        this.category = ''
        this.trade = ''
        this.port = ''
        this.variety = ''
        this.setRouter()
      },

      /**
       * 搜索条件组件内部改变
       */
      change ({checks, item = {}}) {
        if (item.type === 'variety') {
          this.category = ''
        }

        if (item.type === 'trade') {
          this.port = ''
        }

        this[item.type] = checks[item.type].join(',')
        this.setRouter()
      },

      /**
       * 页码改变
       * @param p
       */
      changePage (p) {
        this.page = p
        this.setRouter()
      },

      /**
       * 路由设置
       */
      setRouter () {
        const q = {
          page: this.page,
          filed: this.oSort.filed,
          sortStyle: this.oSort.sortStyle,
          showType: this.showType,
          variety: this.variety,
          category: this.category,
          q: this.keyword,
          p: this.port,
          trade: this.trade
        }

        this.$router.push({
          path: '/mall',
          query: ObjectMap(q),
          hash: 'lists'
        })
      }
    },
    components: {
      SearchProduct,
      SortProduct,
      Recommend,
      Product,
      ProductCard
    },

    // 监视用户登录
    watch: {
      async user () {
        if (this.user.userId) {
          this.getGoods()
        }
      }
    },

    computed: {
      user () {
        return this.$store.state.user.user
      }
    }
  }
</script>

<style lang="scss" type="text/scss" scoped>

  .banner {
    height: 380px;
    overflow: hidden;

    a {
      display: block;
      width: 100%;
    }

    img {
      height: 380px;
      transform: translateX(-50%);
      position: relative;
      left: 50%;
    }
  }

  .search-product {
    margin: 10px 0 20px;
  }

  .search-total {
    color: #9e9e9e;

    .keyword {
      max-width: 100px;
      vertical-align: middle;
    }
  }

  .single-product {
    margin-top: 20px;
    .product {
      margin-bottom: 10px;
    }
  }

  .grid-product {
    margin-top: 20px;
    overflow: hidden;
    margin-left: -16px;
    .product {
      float: left;
      margin-left: 16px;
      margin-bottom: 18px;
    }
  }


</style>
